package org.elec.mac.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.constants.Constants;
import org.elec.mac.ehcache.TokenEhCache;
import org.elec.mac.entity.SessionUser;
import org.elec.mac.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * Created by Bean on 2017/5/12.
 */
@Slf4j
@Controller
public class LoginController extends BaseController {

    @Autowired
    private TokenEhCache tokenEhCache;

    @RequestMapping(value = "/login.do")
    public String loginHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        String action = this.getParameter(request, "action");

        if("do".equals(action)) {
            String username = this.getParameter(request, "username");
            String password = this.getParameter(request, "password");

            if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
                model.put("errMsg", "用户名或密码不能为空！");
                return "login";
            }

            // 效验用户名密码
            EhCacheCacheManager manager = cacheConfiguration.ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
            Cache userCache = manager.getCache("userCache");
            SysUser sysUser = userCache.get(username, SysUser.class);
            if(sysUser == null || !sysUser.getPassword().equals(DigestUtils.md5Hex(password))) {
                model.put("errMsg", "该用户不存在或已失效！");
                return "login";
            }
            // 获取用户所拥有的角色列表
            Cache roleUserCache = manager.getCache("roleUserCache");
            Long roleId = roleUserCache.get(sysUser.getId(), Long.class);
            //
            if(roleId == null || roleId == 0){
                model.put("errMsg", "用户尚未分配角色无法登录!");
                return "login";
            }
            // 验证用户重复登录
            Cache userTokenCache = manager.getCache("userTokenCache");
            Cache authorityCache = manager.getCache("authorityCache");
            String token = userTokenCache.get(username, String.class);
            if (StringUtils.isNotBlank(token)) {
                userTokenCache.evict(username);
                authorityCache.evict(token);
            }
            token = tokenEhCache.createToken(username);
            userTokenCache.put(username, token);
            authorityCache.put(token, username);
            SessionUser sessionUser = new SessionUser();
            sessionUser.setToken(token);
            setSessionObject(request, Constants.SESSION_USER_KEY, sessionUser);
            return "redirect:/main.do";
        }

        return "login";
    }

    @RequestMapping("/login_out.do")
    public String loginOutHandler(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute(Constants.SESSION_USER_KEY);
        return "redirect:login.do";
    }
}
